package _05_二叉树;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/
 */
public class _589_N叉树的前序遍历 {

    // 递归
    public List<Integer> preorder1(Node root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;

        preorder(root, list);
        return list;
    }

    public void preorder(Node root, List<Integer> list) {
        if (root == null) return;

        list.add(root.val);

        List<Node> nodes = root.children;
        if (nodes != null && !nodes.isEmpty()) {
            for (Node node : nodes) {
                preorder(node, list);
            }
        }
    }

    // 迭代
    public List<Integer> preorder(Node root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<Node> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            root = stack.pop();

            list.add(root.val);

            List<Node> nodes = root.children;
            if (nodes != null && !nodes.isEmpty()) {
                for (int i = nodes.size() - 1; i >= 0 ; i--) {
                    stack.push(nodes.get(i));
                }
            }
        }
        return list;
    }
}
